#include <string>
#include <boost/lexical_cast.hpp>

#include "RequestHandler.h"
#include "IndexPage.h"
#include "Request.h"
#include "Reply.h"

#include "../HtmlGenerator/HtmlConverter.h"
#include "../HtmlGenerator/ImageLoader.h"
#include "GameBase.h"

using namespace std;


void RequestHandler::HandleRequest(const Request &req, Reply &rep)
{
	const char *contentType = "text/html";
	try
	{
		//Generating content.
		UriParser uri(req.uri.c_str());
		switch (uri.GetType())
		{
			case UriParser::GetFile:
				{
					ImageLoader::AppendImage(uri.GetFileName(), rep.content);
					contentType = "image/bitmap";
					break;
				}

			case UriParser::ProcessAction:
				{
					Game *game;
					Player player;
					GameBase::GetRef()->ProcessRequest(uri, game, player);
					HtmlConverter::GenerateGamePage(game, player, rep.content);
					break;
				}
			case UriParser::ShowMuzzle:
				{
					HtmlConverter::GenerateMuzzle(rep.content);
					break;
				}
			default:
				throw std::runtime_error("Unknown action");
		}
		//Filling reply.
		rep.status = Reply::Ok;
	}
	catch (std::exception &ex)
	{
		rep.content = ex.what();
		//rep.status = Reply::InternalServerError;
	}
	rep.headers.resize(2);
	rep.headers[0].name = "Content-Length";
	rep.headers[0].value = boost::lexical_cast<string>(rep.content.size());
	rep.headers[1].name = "Content-Type";
	rep.headers[1].value = contentType;
}
